package com.jh.fcsm.controller.inf.rest;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jh.fcsm.beans.inf.InfApp;
import com.jh.fcsm.beans.inf.InfLogRecord;
import com.jh.fcsm.beans.inf.InfTask;
import com.jh.fcsm.beans.inf.vo.PlatformRequestVo;
import com.jh.fcsm.beans.inf.vo.PlatformResultVo;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.constant.Constant;
import com.jh.fcsm.service.inf.InfLogRecordService;
import com.jh.fcsm.service.inf.InfTaskService;
import com.jh.fcsm.service.inf.ThreePartyService;
import com.jh.fcsm.util.security.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 第三方调用系统统一入口
 *
 * @author linqiang
 */
@RestController
@RequestMapping("/rest/foreign")
@Api(value = "第三方系统调用本系统接口数据统一入口", tags = "第三方系统调用本系统接口数据统一入口")
public class ThreePartyController {

    @Autowired
    private ThreePartyService threePartyService;
    @Autowired
    private InfLogRecordService infLogRecordService;

    @Autowired
    private InfTaskService infTaskService;

    /**
     * timeAffix hash256加密
     *
     * @param request
     * @return
     */
    @PostMapping("/entrance")
    @ResponseBody
    @ApiOperation(value = "GM2D对外开放入口", notes = "GM2D对外开放入口")
    public PlatformResultVo entrance(@RequestBody PlatformRequestVo request) {
        // 方法开始时间
        Long beginTime = System.currentTimeMillis();
        PlatformResultVo result = new PlatformResultVo();
        InfLogRecord log = setLogRecord(request);

        InfApp app = null;
        try {
            app = threePartyService.checkRequest(request);

            Object obj = handle(request);
            result.setData(obj);
            result.setStatus("200");
            result.setMessage("成功");
            log.setAppName(app.getAppName());
        } catch (Exception e) {
            result.setStatus("500");
            result.setMessage(e.getMessage());
            if (app == null) {
                app = new InfApp();
                app.setId(log.getAppKey());
            }
        }
        Long endTime = System.currentTimeMillis();
        log.setUseTimes(endTime - beginTime);
        log.setFlag("200".equals(result.getStatus()) ? Constant.YES : Constant.NO);
        log.setErrorMsg(result.getMessage());
        log.setId(UUIDUtils.getUUID());
        log.setMethod(request.getMethod());

        infLogRecordService.insert(log);


        return result;
    }

    /**
     * 业务处理
     *
     * @param request
     * @return
     */
    private Object handle(PlatformRequestVo request) {
        List<InfTask> taskList = infTaskService.getScriptByMethod(request.getMethod());
        if (CollectionUtils.isEmpty(taskList)) {
            return null;
        }
        int rows = 0;
        int maxRow = 500;
        JSONArray data = request.getParam().getJSONArray("data");
        if (data.size() == 0) {
            throw new ServiceException("未传入数据");
        }
        int page = 0;
        if (data.size() > maxRow) {
            page = data.size() / maxRow;
        }

        if (page != 0) {
            for (int i = 0; i < page; i++) {
                rows += batchExec(new JSONArray(data.subList(i * maxRow, ((i + 1) * maxRow))), taskList);
            }
            if (page * maxRow != data.size()) {
                rows += batchExec(new JSONArray(data.subList(page * maxRow, data.size())), taskList);
            }
        } else {
            rows += batchExec(data, taskList);
        }
        return rows;
    }

    private int batchExec(JSONArray data, List<InfTask> taskList) {
        return threePartyService.execMethodTask(data, taskList);
    }


    /**
     * 设置日志
     *
     * @param request
     */
    private InfLogRecord setLogRecord(PlatformRequestVo request) {
        InfLogRecord log = new InfLogRecord();
        log.setAppKey(request.getAppKey());
        log.setMethod(request.getMethod());
        log.setCreateTime(new Date());
        log.setUpdateTime(new Date());
        log.setYn(Constant.YES);
        log.setCreateUser(request.getAppKey());
        log.setUpdateUser(request.getAppKey());
        log.setCreateUserNickname(request.getAppKey());
        log.setUpdateUserNickname(request.getAppKey());
        log.setParams(JSONObject.toJSONString(request));
        return log;
    }
}
